function matrix_stats_plot(stats_file, titles_file, ratings_file, skip)
% Renders histograms for a matrix.stats file (see Makefile).
% stats_file is taken relative to the parent of the src folder.
% titles_file is a a file like netflix_titles (see Makefile)
%             (also rel to src folder).
% ratings_file is a file like num_movie_ratings_training_set.txt (see Makefile)
% skip: only render every skip'th graph (save time).

% Read in titles list.
titles_fid = fopen(['../' titles_file], 'r');
titles = {};
while 1
  line = fgetl(titles_fid);
  if ~ischar(line), break, end
  titles{end+1} = line;
end
fclose(titles_fid);
num_titles = length(titles)

% Last row is summary row.
titles{end+1} = 'total';

% Read in ratings file.
ratings = load(['../' ratings_file]);
assert(length(ratings) == num_titles)

out_file = [stats_file '.html']
out_dir = [stats_file '_files/']

out_fid = fopen(['../' out_file], 'w');
fwrite(out_fid, ['<html><head><title>' stats_file '</title></head><body>']);

in_fid = fopen(['../' stats_file], 'r');
row = 0;
while 1
  row = row + 1;

  % Read line.
  line = fgetl(in_fid);
  if ~ischar(line)
    break
  end

  % Skip rows (too many), but always include the totals row.
  if mod(row, skip) == 1 || row == num_titles + 1
    % The bins are the last thing on the line, following 'bins='.
    % Keep the start of the line (remain) for later.
    [bin_string, remain] = strtok(fliplr(line), '=');
    bins = str2num(fliplr(bin_string));

    bin_count = length(bins);
    if mod(bin_count, 2) == 1
      error 'odd number of bins'
    end

    % Each row of hist is a value, count pair.
    hist = reshape(bins,2,bin_count/2)';

    % Plot to image file.
    % Unfortunately, Matlab dies randomly here.
    img_file = [out_dir num2str(row) '.png'];
    try 
      figure
      plot(hist(:,1),hist(:,2))
      num_ratings = 0;
      if row > num_titles
        num_ratings = sum(ratings(:,2));
      else
        num_ratings = ratings(row,2);
        assert(ratings(row,1) == row)
      end
      title([num2str(row) ':' titles{row} '(' num2str(num_ratings) ')']);
      set(gcf, 'PaperPositionMode', 'auto', ...
               'Resize', 'off', ...
               'Position', [0 0 300 200]);
      print('-dpng', ['../' img_file]);
    catch
      disp('failed to write an image; trying to continue.')
    end

    % Put in file. The image file path is relative to the HTML file,
    % not the src directory, so remove the leading ../, if there is one.
    fwrite(out_fid, ['<img src="' strrep(img_file, '../', '') '"']);

    % Write the start of the line as the "alt" (tool tip).
    fwrite(out_fid, [' alt="' fliplr(remain) '"/>']);
  end
end
fclose(in_fid);

fwrite(out_fid, '</body></html>');
fclose(out_fid);

